<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>知识测验 - 渐进学习平台</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <style>
    /* 基础样式 */
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
    }

    body {
      background-color: #f5f7fa;
      color: #333;
      line-height: 1.6;
      min-height: 100vh;
      display: flex;
    }

    .container {
      display: flex;
      width: 100%;
      max-width: 1400px;
      margin: 0 auto;
      padding: 20px;
      gap: 20px;
    }

    /* 头部样式 */
    header {
      background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
      color: white;
      padding: 15px 0;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      z-index: 100;
    }

    .header-content {
      max-width: 1400px;
      margin: 0 auto;
      padding: 0 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .logo {
      font-size: 24px;
      font-weight: bold;
      display: flex;
      align-items: center;
      gap: 10px;
    }

    .exam-info {
      display: flex;
      gap: 30px;
    }

    .info-item {
      display: flex;
      flex-direction: column;
      align-items: center;
    }

    .info-label {
      font-size: 14px;
      opacity: 0.9;
    }

    .info-value {
      font-size: 18px;
      font-weight: bold;
      margin-top: 5px;
    }

    .timer {
      background: rgba(255, 255, 255, 0.2);
      padding: 8px 15px;
      border-radius: 20px;
      font-weight: bold;
      display: flex;
      align-items: center;
      gap: 8px;
    }

    /* 左侧导航栏 */
    .sidebar {
      width: 280px;
      background: white;
      border-radius: 12px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
      padding: 20px;
      height: calc(100vh - 100px);
      position: sticky;
      top: 90px;
      overflow-y: auto;
    }

    .question-nav {
      margin-bottom: 25px;
    }

    .nav-title {
      font-size: 16px;
      font-weight: 600;
      margin-bottom: 15px;
      color: #444;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .question-grid {
      display: grid;
      grid-template-columns: repeat(5, 1fr);
      gap: 10px;
    }

    .question-number {
      width: 40px;
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #f0f2f5;
      border-radius: 8px;
      font-weight: 500;
      cursor: pointer;
      transition: all 0.2s;
      border: 2px solid transparent;
      position: relative;
    }

    .question-number:hover {
      background: #e1e5eb;
    }

    .question-number.current {
      background: #6a11cb;
      color: white;
      border-color: #6a11cb;
    }

    .question-number.answered {
      background: #4CAF50;
      color: white;
      border-color: #4CAF50;
    }

    .question-number.marked {
      border-color: #FF9800;
    }

    /* 标记指示器 - 右上角小圆点 */
    .mark-indicator {
      position: absolute;
      top: -3px;
      right: -3px;
      width: 12px;
      height: 12px;
      background: #FF9800;
      border-radius: 50%;
      border: 2px solid white;
      display: none;
    }

    .question-number.marked .mark-indicator {
      display: block;
    }

    .exam-actions {
      display: flex;
      flex-direction: column;
      gap: 12px;
    }

    .action-btn {
      padding: 12px 15px;
      border: none;
      border-radius: 8px;
      background: #f0f2f5;
      color: #444;
      font-weight: 500;
      cursor: pointer;
      transition: all 0.2s;
      display: flex;
      align-items: center;
      gap: 10px;
    }

    .action-btn:hover {
      background: #e1e5eb;
    }

    .action-btn.primary {
      background: #6a11cb;
      color: white;
    }

    .action-btn.primary:hover {
      background: #5a0db3;
    }

    /* 开始考试按钮 */
    .start-exam-btn {
      background: linear-gradient(135deg, #4CAF50, #45a049);
      color: white;
      border: none;
      border-radius: 8px;
      padding: 15px 30px;
      font-size: 18px;
      font-weight: bold;
      cursor: pointer;
      transition: all 0.3s;
      display: flex;
      align-items: center;
      gap: 10px;
      margin: 20px auto;
    }

    .start-exam-btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 15px rgba(76, 175, 80, 0.4);
    }

    /* 主内容区 */
    .main-content {
      flex: 1;
      display: flex;
      flex-direction: column;
    }

    .exam-instructions {
      background: white;
      border-radius: 12px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
      padding: 30px;
      margin-bottom: 20px;
      text-align: center;
    }

    .instructions-title {
      font-size: 24px;
      font-weight: bold;
      margin-bottom: 20px;
      color: #6a11cb;
    }

    .instructions-content {
      line-height: 1.8;
      margin-bottom: 30px;
      text-align: left;
      max-width: 800px;
      margin-left: auto;
      margin-right: auto;
    }

    .question-container {
      background: white;
      border-radius: 12px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
      padding: 30px;
      margin-bottom: 20px;
      flex: 1;
      display: none;
    }

    .question-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 25px;
    }

    .question-title {
      font-size: 18px;
      font-weight: 600;
      color: #444;
    }

    .question-meta {
      display: flex;
      gap: 15px;
      color: #666;
      font-size: 14px;
    }

    .mark-btn {
      background: none;
      border: none;
      color: #FF9800;
      cursor: pointer;
      display: flex;
      align-items: center;
      gap: 5px;
      font-size: 14px;
      font-weight: 600;
      padding: 8px 12px;
      border-radius: 6px;
      transition: all 0.2s;
      border: 1px solid #FF9800;
    }

    .mark-btn:hover {
      background: #fff3e0;
    }

    .mark-btn.marked {
      background: #FF9800;
      color: white;
    }

    .question-text {
      font-size: 18px;
      line-height: 1.6;
      margin-bottom: 25px;
      color: #333;
    }

    .options-container {
      display: flex;
      flex-direction: column;
      gap: 15px;
      margin-bottom: 30px;
    }

    .option {
      display: flex;
      align-items: flex-start;
      padding: 15px;
      border: 2px solid #e1e5eb;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.2s;
      background: white;
    }

    .option:hover {
      border-color: #6a11cb;
      background: #f8f9ff;
    }

    .option.selected {
      border-color: #6a11cb;
      background: #f0f2ff;
    }

    .option-marker {
      width: 24px;
      height: 24px;
      border: 2px solid #adb5bd;
      border-radius: 50%;
      margin-right: 15px;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;
      margin-top: 2px;
    }

    .option.selected .option-marker {
      border-color: #6a11cb;
      background: #6a11cb;
      color: white;
    }

    .option-text {
      flex: 1;
    }

    /* 导航按钮 */
    .navigation-buttons {
      display: flex;
      justify-content: space-between;
      margin-top: 30px;
    }

    .nav-btn {
      padding: 12px 25px;
      border: none;
      border-radius: 8px;
      font-weight: 600;
      cursor: pointer;
      transition: all 0.2s;
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .nav-btn.prev {
      background: #f0f2f5;
      color: #444;
    }

    .nav-btn.next {
      background: #6a11cb;
      color: white;
    }

    .nav-btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    /* 底部信息栏 */
    .footer-info {
      background: white;
      border-radius: 12px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
      padding: 15px 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 14px;
      color: #666;
    }

    .legend {
      display: flex;
      gap: 20px;
    }

    .legend-item {
      display: flex;
      align-items: center;
      gap: 5px;
    }

    .color-box {
      width: 16px;
      height: 16px;
      border-radius: 4px;
    }

    .current-box {
      background: #6a11cb;
    }

    .answered-box {
      background: #4CAF50;
    }

    .marked-box {
      border: 2px solid #FF9800;
      background: white;
    }

    /* 专注模式相关样式 */
    .focus-mode-overlay {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(26, 29, 41, 0.95);
      color: white;
      z-index: 10000;
      display: none;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      text-align: center;
      padding: 20px;
    }

    .focus-warning {
      background: #ff6b6b;
      color: white;
      padding: 15px 20px;
      border-radius: 8px;
      margin: 10px 0;
      display: none;
      position: fixed;
      top: 100px;
      left: 50%;
      transform: translateX(-50%);
      z-index: 10001;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
    }

    .focus-stats {
      position: fixed;
      top: 20px;
      right: 20px;
      background: rgba(0,0,0,0.7);
      padding: 10px 15px;
      border-radius: 8px;
      font-size: 14px;
      z-index: 9999;
      color: white;
    }

    .focus-mode-indicator {
      position: fixed;
      top: 20px;
      left: 20px;
      background: #6a11cb;
      color: white;
      padding: 8px 12px;
      border-radius: 20px;
      font-size: 12px;
      z-index: 9999;
      display: none;
    }

    .prison-mode {
      background: #2d1b2b;
    }

    /* 专注模式选择器 */
    .focus-mode-selector {
      background: white;
      border-radius: 12px;
      padding: 25px;
      margin: 20px 0;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    .focus-mode-option {
      display: flex;
      align-items: center;
      padding: 15px;
      border: 2px solid #e1e5eb;
      border-radius: 8px;
      margin-bottom: 15px;
      cursor: pointer;
      transition: all 0.2s;
    }

    .focus-mode-option:hover {
      border-color: #6a11cb;
      background: #f8f9ff;
    }

    .focus-mode-option.selected {
      border-color: #6a11cb;
      background: #f0f2ff;
    }

    .focus-mode-icon {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 15px;
      font-size: 18px;
    }

    .focus-mode-light .focus-mode-icon {
      background: #e8f5e8;
      color: #4CAF50;
    }

    .focus-mode-medium .focus-mode-icon {
      background: #fff3e0;
      color: #FF9800;
    }

    .focus-mode-strict .focus-mode-icon {
      background: #ffebee;
      color: #f44336;
    }

    /* 专注度评分 */
    .focus-score {
      display: flex;
      align-items: center;
      gap: 10px;
      margin-top: 15px;
    }

    .focus-score-bar {
      flex: 1;
      height: 8px;
      background: #e0e0e0;
      border-radius: 4px;
      overflow: hidden;
    }

    .focus-score-fill {
      height: 100%;
      background: linear-gradient(135deg, #4CAF50, #45a049);
      border-radius: 4px;
      transition: width 0.5s;
    }

    .focus-score-value {
      font-weight: bold;
      color: #4CAF50;
      min-width: 40px;
    }

    /* 响应式设计 */
    @media (max-width: 1024px) {
      .container {
        flex-direction: column;
      }

      .sidebar {
        width: 100%;
        position: static;
        height: auto;
      }

      .question-grid {
        grid-template-columns: repeat(10, 1fr);
      }
    }

    @media (max-width: 768px) {
      .header-content {
        flex-direction: column;
        gap: 15px;
      }

      .exam-info {
        width: 100%;
        justify-content: space-between;
      }

      .question-grid {
        grid-template-columns: repeat(5, 1fr);
      }

      .question-header {
        flex-direction: column;
        gap: 10px;
      }

      .navigation-buttons {
        flex-direction: column;
        gap: 10px;
      }

      .nav-btn {
        width: 100%;
        justify-content: center;
      }

      .footer-info {
        flex-direction: column;
        gap: 15px;
        text-align: center;
      }
    }
  </style>
</head>
<body>
<!-- 头部区域 -->
<header>
  <div class="header-content">
    <div class="logo">
      <i class="fas fa-graduation-cap"></i>
      渐进学习平台
    </div>
    <div class="exam-info">
      <div class="info-item">
        <span class="info-label">考试名称</span>
        <span class="info-value">JavaScript高级知识测验</span>
      </div>
      <div class="info-item">
        <span class="info-label">剩余时间</span>
        <div class="timer">
          <i class="far fa-clock"></i>
          <span id="timer">60:00</span>
        </div>
      </div>
    </div>
  </div>
</header>

<!-- 专注模式覆盖层 -->
<div class="focus-mode-overlay" id="focus-mode-overlay">
  <h1>🔒 专注模式已启用</h1>
  <p id="focus-mode-description">您已进入专注学习模式</p>
  <div style="text-align: left; margin: 20px 0; max-width: 500px;">
    <div id="focus-mode-rules">
      <!-- 专注模式规则会动态生成 -->
    </div>
  </div>
  <div class="focus-score" style="justify-content: center; margin: 20px 0;">
    <span>当前专注度:</span>
    <div class="focus-score-bar" style="width: 200px;">
      <div class="focus-score-fill" id="focus-score-fill" style="width: 100%"></div>
    </div>
    <span class="focus-score-value" id="focus-score-value">100%</span>
  </div>
  <button id="exit-focus-btn" style="margin-top: 30px; padding: 10px 20px; background: #ff6b6b; color: white; border: none; border-radius: 5px; cursor: pointer;">
    退出专注模式 (不推荐)
  </button>
</div>

<!-- 离开页面警告 -->
<div class="focus-warning" id="focus-warning">
  ⚠️ 检测到您试图离开考试页面！
</div>

<!-- 专注模式指示器 -->
<div class="focus-mode-indicator" id="focus-mode-indicator">
  <i class="fas fa-lock"></i> 专注模式
</div>

<!-- 专注统计 -->
<div class="focus-stats" id="focus-stats">
  <!-- 专注统计会动态生成 -->
</div>

<!-- 主容器 -->
<div class="container" style="margin-top: 80px;">
  <!-- 左侧导航栏 -->
  <div class="sidebar">
    <div class="question-nav">
      <div class="nav-title">
        <span>题目导航</span>
        <span>已完成: <span id="answered-count">0</span>/5</span>
      </div>
      <div class="question-grid" id="question-nav">
        <!-- 题目导航会通过JavaScript动态生成 -->
      </div>
    </div>

    <div class="exam-actions">
      <button class="action-btn" id="mark-btn">
        <i class="far fa-flag"></i>
        标记本题
      </button>
      <button class="action-btn primary" id="submit-exam">
        <i class="fas fa-paper-plane"></i>
        提交考试
      </button>
    </div>
  </div>

  <!-- 主内容区 -->
  <div class="main-content">
    <!-- 考试说明区域（考试开始前显示） -->
    <div class="exam-instructions" id="exam-instructions">
      <h2 class="instructions-title">JavaScript高级知识测验</h2>
      <div class="instructions-content">
        <p>本次考试包含5道题目，涵盖以下题型：</p>
        <ul style="margin: 15px 0 15px 20px;">
          <li>单选题 - 测试基础概念理解</li>
          <li>多选题 - 考察综合知识掌握</li>
          <li>填空题 - 检验关键术语记忆</li>
          <li>代码题 - 评估实际编码能力</li>
          <li>简答题 - 考察知识综合运用</li>
        </ul>
        <p><strong>考试规则：</strong></p>
        <ul style="margin: 15px 0 15px 20px;">
          <li>考试时间：60分钟</li>
          <li>及格分数：80分（总分100分）</li>
          <li>通过考试可解锁下一个知识点</li>
          <li>考试过程中请勿刷新页面</li>
          <li>可以使用标记功能标记不确定的题目</li>
        </ul>

        <!-- 专注模式选择器 -->
        <div class="focus-mode-selector" id="focus-mode-selector">
          <h3 style="margin-bottom: 20px; color: #444;">选择专注模式</h3>

          <div class="focus-mode-option focus-mode-light" data-mode="light">
            <div class="focus-mode-icon">
              <i class="fas fa-leaf"></i>
            </div>
            <div>
              <h4>轻度模式</h4>
              <p>仅提醒离开行为，适合日常练习</p>
            </div>
          </div>

          <div class="focus-mode-option focus-mode-medium" data-mode="medium">
            <div class="focus-mode-icon">
              <i class="fas fa-balance-scale"></i>
            </div>
            <div>
              <h4>中度模式</h4>
              <p>离开会扣分，但允许紧急情况</p>
            </div>
          </div>

          <div class="focus-mode-option focus-mode-strict" data-mode="strict">
            <div class="focus-mode-icon">
              <i class="fas fa-lock"></i>
            </div>
            <div>
              <h4>严格模式</h4>
              <p>接近"监狱"模式，用于重要考试</p>
            </div>
          </div>
        </div>

        <p>准备好后，请点击下方按钮开始考试。</p>
      </div>
      <button class="start-exam-btn" id="start-exam-btn">
        <i class="fas fa-play-circle"></i>
        开始考试
      </button>
    </div>

    <!-- 题目容器（考试开始后显示） -->
    <div class="question-container" id="question-container">
      <div class="question-header">
        <div class="question-title">题目 <span id="current-q-num">1</span> / 5</div>
        <div class="question-meta">
          <span>分值: <strong id="question-points">0</strong> 分</span>
          <span id="question-type">单选题</span>
          <button class="mark-btn" id="toggle-mark">
            <i class="far fa-flag"></i>
            标记本题
          </button>
        </div>
      </div>

      <div class="question-text" id="question-text">
        <!-- 题目内容会通过JavaScript动态生成 -->
      </div>

      <div class="options-container" id="options-container">
        <!-- 选项/输入区域会通过JavaScript动态生成 -->
      </div>

      <div class="navigation-buttons">
        <button class="nav-btn prev" id="prev-btn">
          <i class="fas fa-chevron-left"></i>
          上一题
        </button>
        <button class="nav-btn next" id="next-btn">
          下一题
          <i class="fas fa-chevron-right"></i>
        </button>
      </div>
    </div>

    <div class="footer-info">
      <div class="legend">
        <div class="legend-item">
          <div class="color-box current-box"></div>
          <span>当前题目</span>
        </div>
        <div class="legend-item">
          <div class="color-box answered-box"></div>
          <span>已回答</span>
        </div>
        <div class="legend-item">
          <div class="color-box marked-box"></div>
          <span>已标记</span>
        </div>
      </div>
      <div>
        考试ID: JS2024001 | 总分: 100分 | 及格: 80分
      </div>
    </div>
  </div>
</div>

<script>
  // 考试数据 - 包含多种题型
  const examData = {
    title: "JavaScript高级知识测验",
    totalQuestions: 5,
    timeLimit: 60, // 分钟
    passScore: 80, // 及格分数
    questions: [
      {
        id: 1,
        text: "以下关于JavaScript闭包的说法，哪一项是正确的？",
        type: "single", // 单选题
        points: 20,
        options: [
          "闭包会阻止垃圾回收机制清理不再使用的变量",
          "闭包只能访问函数内部的变量，不能访问外部变量",
          "每次调用外部函数时，闭包都会重新创建",
          "闭包会导致内存泄漏，应该尽量避免使用"
        ],
        correctAnswer: 0
      },
      {
        id: 2,
        text: "下列哪些方法可以用于实现JavaScript中的继承？（多选）",
        type: "multiple", // 多选题
        points: 20,
        options: [
          "原型链继承",
          "构造函数继承",
          "类继承（ES6）",
          "对象冒充继承"
        ],
        correctAnswer: [0, 1, 2, 3]
      },
      {
        id: 3,
        text: "CSS中，用于设置元素外边距的属性是______。",
        type: "fill-blank", // 填空题
        points: 20,
        correctAnswer: "margin"
      },
      {
        id: 4,
        text: "编写一个函数，实现数组去重功能。",
        type: "code", // 代码题
        points: 20,
        placeholder: "// 请在此处编写代码\nfunction removeDuplicates(arr) {\n  // 你的代码\n}"
      },
      {
        id: 5,
        text: "请解释事件委托(event delegation)的概念及其优势。",
        type: "essay", // 简答题
        points: 20,
        placeholder: "请在此处输入你的答案..."
      }
    ]
  };

  // 考试状态
  const examState = {
    currentQuestion: 0,
    userAnswers: new Array(examData.totalQuestions).fill(null),
    markedQuestions: new Array(examData.totalQuestions).fill(false),
    examStarted: false,
    timeLeft: examData.timeLimit * 60, // 转换为秒
    timerInterval: null
  };

  // 专注模式系统
  const focusSystem = {
    // 当前专注模式
    currentMode: 'light', // light, medium, strict

    // 专注模式配置
    modes: {
      light: {
        name: '轻度模式',
        description: '仅提醒离开行为，适合日常练习',
        penaltyPerLeave: 0, // 每次离开扣分
        maxLeaves: 10, // 最大允许离开次数
        autoSubmit: false, // 是否自动提交
        enableStrictFeatures: false // 是否启用严格功能
      },
      medium: {
        name: '中度模式',
        description: '离开会扣分，但允许紧急情况',
        penaltyPerLeave: 2, // 每次离开扣分百分比
        maxLeaves: 5, // 最大允许离开次数
        autoSubmit: false, // 是否自动提交
        enableStrictFeatures: false
      },
      strict: {
        name: '严格模式',
        description: '接近"监狱"模式，用于重要考试',
        penaltyPerLeave: 5, // 每次离开扣分百分比
        maxLeaves: 3, // 最大允许离开次数
        autoSubmit: true, // 是否自动提交
        enableStrictFeatures: true // 是否启用严格功能
      }
    },

    // 专注状态
    enabled: false,
    leaveCount: 0,
    startTime: null,
    totalFocusTime: 0, // 本次专注时间(秒)
    distractions: 0, // 分心次数
    focusScore: 100, // 专注度评分(0-100)

    // 初始化专注系统
    init() {
      // 设置专注模式选择事件
      this.setupModeSelection();
    },

    // 设置专注模式选择
    setupModeSelection() {
      const modeOptions = document.querySelectorAll('.focus-mode-option');
      modeOptions.forEach(option => {
        option.addEventListener('click', () => {
          // 移除其他选项的选中状态
          modeOptions.forEach(opt => opt.classList.remove('selected'));
          // 设置当前选项为选中状态
          option.classList.add('selected');
          // 更新当前模式
          this.currentMode = option.dataset.mode;
        });
      });

      // 默认选择轻度模式
      document.querySelector('.focus-mode-light').classList.add('selected');
    },

    // 启用专注模式
    enable() {
      this.enabled = true;
      this.startTime = Date.now();
      this.leaveCount = 0;
      this.distractions = 0;
      this.focusScore = 100;

      // 显示专注模式覆盖层
      this.showFocusOverlay();

      // 显示专注模式指示器
      document.getElementById('focus-mode-indicator').style.display = 'block';

      // 添加事件监听器
      this.addEventListeners();

      // 启动专注计时器
      this.startFocusTimer();

      // 更新UI
      this.updateFocusStats();
    },

    // 显示专注模式覆盖层
    showFocusOverlay() {
      const overlay = document.getElementById('focus-mode-overlay');
      const modeConfig = this.modes[this.currentMode];

      // 更新描述
      document.getElementById('focus-mode-description').textContent =
              `您已进入${modeConfig.name}`;

      // 更新规则
      const rulesElement = document.getElementById('focus-mode-rules');
      let rulesHTML = '';

      if (this.currentMode === 'light') {
        rulesHTML = `
                        <ul>
                            <li>离开本页面将收到提醒</li>
                            <li>不会影响您的分数</li>
                            <li>适合日常练习和轻松学习</li>
                        </ul>
                    `;
      } else if (this.currentMode === 'medium') {
        rulesHTML = `
                        <ul>
                            <li>离开本页面将扣除本题分数的${modeConfig.penaltyPerLeave}%</li>
                            <li>离开超过${modeConfig.maxLeaves}次将收到严重警告</li>
                            <li>允许紧急情况退出</li>
                        </ul>
                    `;
      } else if (this.currentMode === 'strict') {
        rulesHTML = `
                        <ul>
                            <li>离开本页面将扣除本题分数的${modeConfig.penaltyPerLeave}%</li>
                            <li>离开超过${modeConfig.maxLeaves}次将自动提交考试</li>
                            <li>禁用右键菜单和部分浏览器功能</li>
                            <li>专注度将严重影响最终评分</li>
                        </ul>
                    `;
      }

      rulesElement.innerHTML = rulesHTML;
      overlay.style.display = 'flex';

      // 3秒后自动隐藏
      setTimeout(() => {
        overlay.style.display = 'none';
      }, 3000);
    },

    // 添加事件监听器
    addEventListeners() {
      window.addEventListener('blur', this.handleWindowBlur.bind(this));
      window.addEventListener('beforeunload', this.handleBeforeUnload.bind(this));
      document.addEventListener('visibilitychange', this.handleVisibilityChange.bind(this));

      // 严格模式下禁用右键菜单
      if (this.modes[this.currentMode].enableStrictFeatures) {
        document.addEventListener('contextmenu', this.disableRightClick.bind(this));
      }

      // 退出按钮事件
      document.getElementById('exit-focus-btn').addEventListener('click', this.exit.bind(this));
    },

    // 处理窗口失去焦点
    handleWindowBlur() {
      if (!this.enabled) return;

      this.leaveCount++;
      this.distractions++;

      const modeConfig = this.modes[this.currentMode];

      // 显示警告
      this.showWarning();

      // 中度及以上模式扣分
      if (this.currentMode !== 'light') {
        this.applyPenalty();
      }

      // 更新专注度评分
      this.updateFocusScore();

      // 严格模式下检查是否自动提交
      if (modeConfig.autoSubmit && this.leaveCount >= modeConfig.maxLeaves) {
        this.autoSubmitExam();
      }

      // 更新UI
      this.updateFocusStats();
    },

    // 显示警告
    showWarning() {
      const warning = document.getElementById('focus-warning');
      const modeConfig = this.modes[this.currentMode];

      if (this.currentMode === 'light') {
        warning.textContent = '⚠️ 检测到您试图离开页面，请保持专注！';
      } else if (this.currentMode === 'medium') {
        warning.textContent = `⚠️ 检测到您试图离开页面！专注度-${modeConfig.penaltyPerLeave}%`;
      } else {
        warning.textContent = `⚠️ 严格模式：离开页面将扣分！剩余离开次数: ${modeConfig.maxLeaves - this.leaveCount}`;
      }

      warning.style.display = 'block';
      setTimeout(() => {
        warning.style.display = 'none';
      }, 3000);
    },

    // 应用离开惩罚
    applyPenalty() {
      const modeConfig = this.modes[this.currentMode];
      // 在实际应用中，这里应该扣除当前题目的分数
      // 这里简化为记录惩罚
      console.log(`因离开页面，扣减分数: ${modeConfig.penaltyPerLeave}%`);
    },

    // 更新专注度评分
    updateFocusScore() {
      // 根据分心次数计算专注度
      const baseScore = 100;
      const penalty = this.distractions * 5; // 每次分心减5%
      this.focusScore = Math.max(0, baseScore - penalty);

      // 更新UI
      document.getElementById('focus-score-fill').style.width = `${this.focusScore}%`;
      document.getElementById('focus-score-value').textContent = `${this.focusScore}%`;
    },

    // 自动提交考试
    autoSubmitExam() {
      alert('您已多次离开考试页面，考试将自动提交！');
      submitExam();
    },

    // 处理页面关闭/刷新
    handleBeforeUnload(e) {
      if (!this.enabled) return;

      e.preventDefault();
      e.returnValue = '您正在专注模式中，确定要离开吗？这将影响您的专注度评分。';
      return e.returnValue;
    },

    // 处理页面可见性变化
    handleVisibilityChange() {
      if (!this.enabled) return;

      if (document.hidden) {
        this.handleWindowBlur();
      }
    },

    // 禁用右键菜单
    disableRightClick(e) {
      if (!this.enabled) return;
      e.preventDefault();
      return false;
    },

    // 启动专注计时器
    startFocusTimer() {
      setInterval(() => {
        if (this.enabled && document.hasFocus()) {
          this.totalFocusTime += 1;
          this.updateFocusStats();
        }
      }, 1000);
    },

    // 更新专注统计
    updateFocusStats() {
      const statsEl = document.getElementById('focus-stats');
      const modeConfig = this.modes[this.currentMode];

      const minutes = Math.floor(this.totalFocusTime / 60);
      const seconds = this.totalFocusTime % 60;

      statsEl.innerHTML = `
                    专注时间: ${minutes}分${seconds}秒<br>
                    专注度: ${this.focusScore}%<br>
                    离开次数: ${this.leaveCount}/${modeConfig.maxLeaves}
                `;
    },

    // 退出专注模式
    exit() {
      if (confirm('确定要退出专注模式吗？这将影响您的专注度评分！')) {
        this.disable();
      }
    },

    // 禁用专注模式
    disable() {
      this.enabled = false;

      // 隐藏UI元素
      document.getElementById('focus-mode-overlay').style.display = 'none';
      document.getElementById('focus-mode-indicator').style.display = 'none';

      // 移除事件监听器
      window.removeEventListener('blur', this.handleWindowBlur);
      window.removeEventListener('beforeunload', this.handleBeforeUnload);
      document.removeEventListener('visibilitychange', this.handleVisibilityChange);
      document.removeEventListener('contextmenu', this.disableRightClick);
    }
  };

  // DOM 元素
  const questionNav = document.getElementById('question-nav');
  const questionText = document.getElementById('question-text');
  const optionsContainer = document.getElementById('options-container');
  const currentQNum = document.getElementById('current-q-num');
  const answeredCount = document.getElementById('answered-count');
  const timerElement = document.getElementById('timer');
  const prevBtn = document.getElementById('prev-btn');
  const nextBtn = document.getElementById('next-btn');
  const submitBtn = document.getElementById('submit-exam');
  const markBtn = document.getElementById('toggle-mark');
  const startExamBtn = document.getElementById('start-exam-btn');
  const examInstructions = document.getElementById('exam-instructions');
  const questionContainer = document.getElementById('question-container');
  const questionPoints = document.getElementById('question-points');
  const questionType = document.getElementById('question-type');

  // 初始化页面
  function initPage() {
    // 初始化专注系统
    focusSystem.init();

    // 生成题目导航
    renderQuestionNav();

    // 添加事件监听器
    startExamBtn.addEventListener('click', startExam);
    prevBtn.addEventListener('click', goToPrevQuestion);
    nextBtn.addEventListener('click', goToNextQuestion);
    submitBtn.addEventListener('click', submitExam);
    markBtn.addEventListener('click', toggleMark);

    // 初始化计时器显示
    updateTimerDisplay();
  }

  // 渲染题目导航
  function renderQuestionNav() {
    questionNav.innerHTML = '';

    for (let i = 0; i < examData.totalQuestions; i++) {
      const qNum = document.createElement('div');
      qNum.className = 'question-number';
      qNum.textContent = i + 1;
      qNum.dataset.index = i;

      // 标记当前题目
      if (i === examState.currentQuestion && examState.examStarted) {
        qNum.classList.add('current');
      }

      // 标记已回答题目
      if (examState.userAnswers[i] !== null) {
        qNum.classList.add('answered');
      }

      // 标记已标记题目
      if (examState.markedQuestions[i]) {
        qNum.classList.add('marked');

        // 添加标记指示器
        const markIndicator = document.createElement('div');
        markIndicator.className = 'mark-indicator';
        qNum.appendChild(markIndicator);
      }

      qNum.addEventListener('click', () => {
        if (examState.examStarted) {
          goToQuestion(i);
        }
      });

      questionNav.appendChild(qNum);
    }
  }

  // 开始考试
  function startExam() {
    examState.examStarted = true;
    examState.startTime = new Date();

    // 启用专注模式
    focusSystem.enable();

    // 隐藏考试说明，显示题目容器
    examInstructions.style.display = 'none';
    questionContainer.style.display = 'block';

    // 显示第一题
    renderQuestion(0);

    // 启动计时器
    startTimer();

    // 更新已回答题目计数
    updateAnsweredCount();
  }

  // 渲染题目
  function renderQuestion(index) {
    if (index < 0 || index >= examData.totalQuestions) return;

    examState.currentQuestion = index;
    currentQNum.textContent = index + 1;

    // 更新导航高亮
    updateNavHighlight();

    // 获取当前题目数据
    const question = examData.questions[index];

    // 渲染题目内容
    questionText.textContent = question.text;

    // 显示题目分值和类型
    questionPoints.textContent = question.points;
    questionType.textContent = getQuestionTypeText(question.type);

    // 根据题目类型渲染不同的输入区域
    renderQuestionByType(question, index);

    // 更新按钮状态
    updateButtonStates();

    // 更新标记按钮状态
    updateMarkButton();
  }

  // 根据题目类型渲染不同的输入区域
  function renderQuestionByType(question, qIndex) {
    optionsContainer.innerHTML = '';

    switch (question.type) {
      case 'single':
      case 'multiple':
        // 选择题
        renderChoiceOptions(question, qIndex);
        break;
      case 'fill-blank':
        // 填空题
        renderFillBlank(question, qIndex);
        break;
      case 'code':
        // 代码题
        renderCodeEditor(question, qIndex);
        break;
      case 'essay':
        // 简答题
        renderEssayArea(question, qIndex);
        break;
    }
  }

  // 渲染选择题选项
  function renderChoiceOptions(question, qIndex) {
    question.options.forEach((option, index) => {
      const optionElement = document.createElement('div');
      optionElement.className = 'option';

      // 如果已选择此选项，添加selected类
      if (
              (question.type === 'single' && examState.userAnswers[qIndex] === index) ||
              (question.type === 'multiple' && examState.userAnswers[qIndex] &&
                      examState.userAnswers[qIndex].includes(index))
      ) {
        optionElement.classList.add('selected');
      }

      optionElement.innerHTML = `
                    <div class="option-marker">${String.fromCharCode(65 + index)}</div>
                    <div class="option-text">${option}</div>
                `;

      optionElement.addEventListener('click', () => {
        handleOptionSelect(qIndex, index, question.type);
      });

      optionsContainer.appendChild(optionElement);
    });
  }

  // 渲染填空题
  function renderFillBlank(question, qIndex) {
    const input = document.createElement('input');
    input.type = 'text';
    input.className = 'fill-blank-input';
    input.placeholder = '请输入答案';

    // 如果已有答案，填充答案
    if (examState.userAnswers[qIndex]) {
      input.value = examState.userAnswers[qIndex];
    }

    input.addEventListener('input', () => {
      examState.userAnswers[qIndex] = input.value;
      updateAnsweredCount();
      updateNavHighlight();
    });

    optionsContainer.appendChild(input);
  }

  // 渲染代码编辑器
  function renderCodeEditor(question, qIndex) {
    const textarea = document.createElement('textarea');
    textarea.className = 'code-editor';
    textarea.placeholder = question.placeholder;

    // 如果已有答案，填充答案
    if (examState.userAnswers[qIndex]) {
      textarea.value = examState.userAnswers[qIndex];
    }

    textarea.addEventListener('input', () => {
      examState.userAnswers[qIndex] = textarea.value;
      updateAnsweredCount();
      updateNavHighlight();
    });

    optionsContainer.appendChild(textarea);
  }

  // 渲染简答题区域
  function renderEssayArea(question, qIndex) {
    const textarea = document.createElement('textarea');
    textarea.className = 'essay-textarea';
    textarea.placeholder = question.placeholder;

    // 如果已有答案，填充答案
    if (examState.userAnswers[qIndex]) {
      textarea.value = examState.userAnswers[qIndex];
    }

    textarea.addEventListener('input', () => {
      examState.userAnswers[qIndex] = textarea.value;
      updateAnsweredCount();
      updateNavHighlight();
    });

    optionsContainer.appendChild(textarea);
  }

  // 处理选项选择
  function handleOptionSelect(qIndex, optionIndex, questionType) {
    if (questionType === 'single') {
      // 单选题
      examState.userAnswers[qIndex] = optionIndex;
    } else if (questionType === 'multiple') {
      // 多选题
      if (!examState.userAnswers[qIndex]) {
        examState.userAnswers[qIndex] = [];
      }

      const answerIndex = examState.userAnswers[qIndex].indexOf(optionIndex);
      if (answerIndex === -1) {
        examState.userAnswers[qIndex].push(optionIndex);
      } else {
        examState.userAnswers[qIndex].splice(answerIndex, 1);
      }
    }

    // 重新渲染当前题目以更新选择状态
    renderQuestion(qIndex);
    updateAnsweredCount();
  }

  // 获取题目类型文本
  function getQuestionTypeText(type) {
    const typeMap = {
      'single': '单选题',
      'multiple': '多选题',
      'fill-blank': '填空题',
      'code': '代码题',
      'essay': '简答题'
    };
    return typeMap[type] || '未知题型';
  }

  // 更新导航高亮
  function updateNavHighlight() {
    const questionNumbers = document.querySelectorAll('.question-number');

    questionNumbers.forEach((qNum, index) => {
      qNum.classList.remove('current');

      if (index === examState.currentQuestion && examState.examStarted) {
        qNum.classList.add('current');
      }

      qNum.classList.remove('answered');
      if (examState.userAnswers[index] !== null) {
        qNum.classList.add('answered');
      }

      qNum.classList.remove('marked');
      if (examState.markedQuestions[index]) {
        qNum.classList.add('marked');
      }
    });
  }

  // 更新按钮状态
  function updateButtonStates() {
    prevBtn.disabled = examState.currentQuestion === 0;
    nextBtn.disabled = examState.currentQuestion === examData.totalQuestions - 1;
  }

  // 更新标记按钮状态
  function updateMarkButton() {
    const currentQIndex = examState.currentQuestion;
    if (examState.markedQuestions[currentQIndex]) {
      markBtn.innerHTML = `<i class="fas fa-flag"></i> 取消标记`;
      markBtn.classList.add('marked');
    } else {
      markBtn.innerHTML = `<i class="far fa-flag"></i> 标记本题`;
      markBtn.classList.remove('marked');
    }
  }

  // 更新已回答题目计数
  function updateAnsweredCount() {
    const answered = examState.userAnswers.filter(answer => answer !== null).length;
    answeredCount.textContent = answered;
  }

  // 跳转到上一题
  function goToPrevQuestion() {
    if (examState.currentQuestion > 0) {
      renderQuestion(examState.currentQuestion - 1);
    }
  }

  // 跳转到下一题
  function goToNextQuestion() {
    if (examState.currentQuestion < examData.totalQuestions - 1) {
      renderQuestion(examState.currentQuestion + 1);
    }
  }

  // 跳转到指定题目
  function goToQuestion(index) {
    renderQuestion(index);
  }

  // 标记/取消标记题目
  function toggleMark() {
    const currentQIndex = examState.currentQuestion;
    examState.markedQuestions[currentQIndex] = !examState.markedQuestions[currentQIndex];

    // 更新UI
    updateMarkButton();
    renderQuestionNav();
  }

  // 启动计时器
  function startTimer() {
    examState.timerInterval = setInterval(() => {
      examState.timeLeft--;

      if (examState.timeLeft <= 0) {
        clearInterval(examState.timerInterval);
        submitExam();
        return;
      }

      updateTimerDisplay();

      // 最后5分钟变红
      if (examState.timeLeft <= 300) {
        timerElement.style.color = '#ff6b6b';
      }
    }, 1000);
  }

  // 更新计时器显示
  function updateTimerDisplay() {
    const minutes = Math.floor(examState.timeLeft / 60);
    const seconds = examState.timeLeft % 60;
    timerElement.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
  }

  // 提交考试
  function submitExam() {
    // 停止计时器
    if (examState.timerInterval) {
      clearInterval(examState.timerInterval);
    }

    // 禁用专注模式
    if (focusSystem.enabled) {
      focusSystem.disable();
    }

    // 计算得分
    let totalScore = 0;
    let earnedScore = 0;

    examData.questions.forEach((question, index) => {
      totalScore += question.points;

      // 根据题目类型计算得分
      switch (question.type) {
        case 'single':
          // 单选题
          if (examState.userAnswers[index] === question.correctAnswer) {
            earnedScore += question.points;
          }
          break;
        case 'multiple':
          // 多选题
          if (examState.userAnswers[index] &&
                  JSON.stringify(examState.userAnswers[index].sort()) ===
                  JSON.stringify(question.correctAnswer.sort())) {
            earnedScore += question.points;
          }
          break;
        case 'fill-blank':
          // 填空题
          if (examState.userAnswers[index] &&
                  examState.userAnswers[index].toLowerCase().trim() ===
                  question.correctAnswer.toLowerCase().trim()) {
            earnedScore += question.points;
          }
          break;
        case 'code':
        case 'essay':
          // 代码题和简答题 - 在实际应用中应由教师评分
          // 这里简化为只要有答案就给一半分数
          if (examState.userAnswers[index] && examState.userAnswers[index].trim() !== '') {
            earnedScore += question.points * 0.5;
          }
          break;
      }
    });

    // 计算百分比
    const scorePercentage = Math.round((earnedScore / totalScore) * 100);

    // 根据得分决定跳转页面
    if (scorePercentage >= examData.passScore) {
      // 考试通过
      alert(`恭喜！您通过了考试，得分：${scorePercentage}分。即将进入下一个知识点...`);
      // 在实际应用中，这里应该跳转到下一个知识点页面
      // window.location.href = '/next-knowledge-point';
    } else {
      // 考试失败
      alert(`很遗憾，您未通过考试，得分：${scorePercentage}分。请继续学习并重新参加考试。`);
      // 在实际应用中，这里应该提供重考选项
      // window.location.href = '/retake-exam';
    }
  }

  // 初始化页面
  document.addEventListener('DOMContentLoaded', initPage);
</script>
</body>
</html>